<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="分类名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="父分类id" prop="parentCid">-->
<!--        <el-input-->
<!--          v-model="queryParams.parentCid"-->
<!--          placeholder="请输入父分类id"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="层级" prop="catLevel">
        <el-input
          v-model="queryParams.catLevel"
          placeholder="请输入层级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="是否显示[0-显示，1-不显示]" prop="showStatus">
        <el-select
          v-model="queryParams.showStatus"
          placeholder="请选择是否显示[0-显示，1-不显示]"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_show_hide"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd(row)"
          v-hasPermi="['product:category:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:category:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:category:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:category:export']"
          >导出</el-button
        >
      </el-col> -->
      <!-- <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      row-key="catId"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column label="序号" align="center" prop="catId" /> -->
      <el-table-column
        label="分类名称"
        align="center"
        prop="name"
        width="160"
      />
      <!-- <el-table-column label="父分类id" align="center" prop="parentCid" /> -->
      <!-- <el-table-column label="层级" align="center" prop="catLevel" /> -->
      <el-table-column label="是否显示" align="center" prop="showStatus">
        <template #default="scope">
          <dict-tag :options="sys_show_hide" :value="scope.row.showStatus" />
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- 注意PLUS版本type=text已废弃，需要用link -->
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:category:remove']"
            >删除</el-button
          > -->
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleAdd(scope.row)"
            v-if="scope.row.catLevel != 3"
            v-hasPermi="['product:category:add']"
            >添加</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:category:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:category:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品分类对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父级分类" v-if="form.parentCid != 0">
          <el-tree-select
            :data="menuOptions"
            :props="{ value: 'catId', label: 'name', children: 'children' }"
            value-key="catId"
            v-model="form.parentCid"
            placeholder="选择上级菜单"
            check-strictly
            filterable
          >
          </el-tree-select>
          <!-- <el-input v-model="form.name" placeholder="请输入分类名称" /> -->
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <!-- <el-form-item label="父分类id" prop="parentCid">
          <el-input v-model="form.parentCid" placeholder="请输入父分类id" />
        </el-form-item> -->
        <!-- <el-form-item label="层级" prop="catLevel">
          <el-input v-model="form.catLevel" placeholder="请输入层级" />
        </el-form-item> -->
        <el-form-item label="是否显示" prop="showStatus">
          <el-radio-group v-model="form.showStatus">
            <el-radio
              v-for="dict in sys_show_hide"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
/**
 *  !!!!!!! PS: Element-UI Plus3更改
 *  1. el-button：type=“text”已废弃，大小没有mini，
 *  2. el-dialog： ：visiable.sync无效，需要用v-model控制弹窗显示
 *  3. icon: 去掉了el-icon的前缀，且首字母要大写，部分图表不显示看文档
 *  4. slot: 原来的slot="xx"，都要变成 #xx
 */
import {
  listCategory,
  getCategory,
  delCategory,
  addCategory,
  updateCategory,
} from "@/api/mall/server/product/cate";
import { reactive, ref, toRefs, getCurrentInstance } from "vue";
// vue3中获取this的方法
const { proxy } = getCurrentInstance();
const { sys_show_hide } = proxy.useDict("sys_show_hide");
// 查询list
const total = ref(0);
const loading = ref(false);
const list = ref([]);
const menuOptions = ref([]);
const isExpandAll = ref(false);
// 单选多选
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
// 对话弹窗
const title = ref("");
const open = ref(false);
// 查询参数和表单
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {},
});
// 为什么用toRefs？
const { queryParams, form, rules } = toRefs(data);
// 列表查询
const getList = async () => {
  loading.value = true;
  const res = await listCategory(queryParams.value);
  list.value = res.rows;
  // list.value = proxy.handleTree(res.rows, "catId", "parentCid", "children")
  total.value = res.total;
  loading.value = false;
  let _list = JSON.parse(JSON.stringify(res.rows));
  _list.forEach((item) => {
    if (item.children) {
      item.children.forEach((item) => {
        item.children = [];
      });
    }
    menuOptions.value.push(item);
  });
  console.log(menuOptions.value);
};
// 取消
const cancel = () => {
  open.value = false;
  reset();
};

// 表单重置
const reset = () => {
  form.value = {
    catId: undefined,
    name: undefined,
    parentCid: undefined,
    catLevel: undefined,
    showStatus: undefined,
    sort: undefined,
  };
};

// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

// 表单重置
const resetQuery = () => {
  proxy.resetForm("queryRef");
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.catId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

// 添加弹窗
const handleAdd = (row) => {
  reset();
  // 处理参数,添加的时候，层级加一
  if (row != null && row.catId) {
    form.value.parentCid = row.catId;
    form.value.catLevel = row.catLevel + 1;
  } else {
    form.value.parentCid = 0;
  }
  open.value = true;
  title.value = "添加商品分类";
};
// 修改操作
const handleUpdate = async (row) => {
  reset();
  const catId = row.catId || ids.value;
  const res = await getCategory(catId);
  form.value = res.data;
  open.value = true;
  title.value = "修改商品分类";
};
// 表单提交
const submitForm = () => {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.catId != undefined) {
        updateCategory(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCategory(form.value).then((res) => {
          proxy.$modal.msgSuccess("添加成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

// 删除
const handleDelete = (row) => {
  const ids = row.catId || ids.value;
  proxy.$modal
    .confirm(`是否确认删除编号位${ids}的数据项?`)
    .then((res) => {
      return delCategory(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}
// 初始调用
getList();
</script>
